const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'

const httpInceptor = {
    invoke(options){
        if(!options.url.startsWith('http')){
            options.url = baseURL + options.url
        }
        options.timeout = 5000
        options.header = {
            ...options.header,
            'source-client':'miniapp'
        }

    }
}

uni.addInterceptor('request',httpInceptor)
uni.addInterceptor('uploadFile',httpInceptor)

export const http = (options)=>{
    return new Promise((resolve,reject)=>{
        uni.request({
            ...options,
            success(res){
                if(res.statusCode>=200 && res.statusCode<300){
                    resolve(res.data)
                }else if(res.statusCode === 401){
                    uni.navigateTo({url:'/pages/index/index'})
                    reject(res)
                }else{
                    uni.showToast({
                        icon:'none',
                        title:res.data.msg || '请求错误'
                })
                reject(res)
            }},
            fail(err){
                uni.showToast({
                    icon:'none',
                    title:'网络错误'
            })
                reject(err)
            }
        })
    })
}